package Class002;
import java.util.Arrays;

//社会的基尼系数是一个在0~1的小数
//基尼系数为1，代表1个人掌握社会全部财富
//基尼系数为0，代表所有人财富完全一样
//当基尼系数为0.5，认为贫富差距非常大，可能会造成社会动荡

//概念：
//1.和其他人的财富差值绝对值总和
//2.财富总和
//基尼系数计算方式：差值总和 / (2 * 人数 * 财富总和)
//实验：每次每个人给其他一个人1元，很多轮后的基尼系数是什么？
//能不能用代码模拟
public class SocietyExperiment {
    public static int NUM_OF_PEOPLE = 100;
    public static int ROUNDS = 1000000;
    public static int GIVEMONEY = 1;
    public static int[] MONEY_TABLE = new int[NUM_OF_PEOPLE];

    public static void main(String[] args) {
        initTable();
        for(int i = 0; i < ROUNDS; i++) {
            distributeMoney();
        }
        calculateGini(ROUNDS);
        Arrays.sort(MONEY_TABLE);
        System.out.println("每个人的财富值(从小到大):");
        printTable();
    }

    public static void printTable() {
        int index = 0;
        while(index < NUM_OF_PEOPLE) {
            System.out.print(MONEY_TABLE[index++] + " ");
            if(index % 9 == 0) {
                System.out.println();
            }
        }
    }

    public static void initTable() {
        Arrays.fill(MONEY_TABLE, 100);
    }

    public static void distributeMoney() {
        for(int i = 0; i < NUM_OF_PEOPLE; i++) {
            if(MONEY_TABLE[i] < GIVEMONEY) continue;
            int random = (int) (100 * Math.random());
            while(random == i) {
                random = (int) (100 * Math.random());
            }
            MONEY_TABLE[i] -= GIVEMONEY;
            MONEY_TABLE[random] += GIVEMONEY;
        }
    }

    public static void calculateGini(int curRound) {
        int totalDiff = 0;
        int totalSum = 0;
        double gini = 0;
        for(int i = 0; i < NUM_OF_PEOPLE; i++) {
            totalSum += MONEY_TABLE[i];
            for(int j = 0; j < NUM_OF_PEOPLE; j++) {
                if (j != i) {
                    totalDiff += Math.abs(MONEY_TABLE[i] - MONEY_TABLE[j]);
                }
            }
        }
        gini =  (totalDiff * 1.0) / (2 * NUM_OF_PEOPLE * totalSum);
        System.out.println("cur round: " + curRound + ", gini = " + gini);
    }
}
